package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.声明队列
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("123.207.74.192");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("bite");
        Connection connection = connectionFactory.newConnection();
        // 2.创建Channel
        Channel channel = connection.createChannel();
        // 3.声明队列(可以省略,但不建议)
        channel.queueDeclare("hello",true,false,false,null); // 已存在则不会创建,不存在则会创建,
                                                // 不声明若队列不存在,则会报错,影响生产环境
        // 4.消费消息
        /**
         *     String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
         * 参数说明
         * queue: 队列名称
         * autoAck: 是否自动确认
         * callback: 接收到消息后,执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 从队列中接收到信息就会执行的内容
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /**
                 * consumerTag: 消费者标签
                 * envelope: 封装信息,队列名称,交换机等
                 * propertie: 配置信息
                 * body: 消息内容
                 */
                // TODO
                System.out.println("接收消息: "+new String(body));
            }
        };
        channel.basicConsume("hello",true,consumer);

        // 等待程序执行完成
        Thread.sleep(2000);
        // 5.释放资源
//        channel.close();
//        connection.close();
    }
}
